package dbUtils

import (
	"fmt"
	"gitee.com/lv_baobao/gcore/helper"
	"github.com/ahmetb/go-linq/v3"
	"strings"
)

type IQueryable interface {
	From(tableName string) IQueryable
	Take(size int32) IQueryable
	WhereIf(condition string, arg interface{}, condtion bool) IQueryable
	Where(condition string, arg interface{}) IQueryable
	WhereIn(fieldName string, args []interface{}, condition bool) IQueryable

	In(fieldName string, args ...interface{}) IQueryable
	Order(orderField string) IQueryable
	OrderByDesc(orderField string) IQueryable
	Page(pageIndex int, pageSize int, beansPtr interface{}) *helper.QueryResult
	List(beansPtr interface{})
	FirstOrDefault(beanPtr interface{})
	Delete() int64
	Count() int64
	Set(field string, arg interface{}) IQueryable
	Update() bool
	GetWhereMap() map[string]interface{}
	SelectFields(fields string) IQueryable
}

//func ToInterfaceArray[T any](args []T) []interface{} {
//	var interfaceSlice []interface{} = make([]interface{}, len(args))
//	for i, d := range args {
//		interfaceSlice[i] = d
//	}
//	return interfaceSlice
//}

func ToInterfaceArray(source interface{}) []interface{} {
	res := make([]interface{}, 0)
	linq.From(source).ToSlice(&res)
	return res
}

func getWhereKeysAndArgsAndWhereSql(queryable IQueryable) ([]string, []interface{}, string) {
	var whereArgs = make([]interface{}, 0)
	var whereKeys = make([]string, 0)
	whereMap := queryable.GetWhereMap()
	if len(whereMap) > 0 {
		for k := range whereMap {
			whereKeys = append(whereKeys, k)
		}
	}
	for _, key := range whereKeys {
		elems := whereMap[key]
		if elems != nil {
			if ids, ok := elems.([]interface{}); ok {
				for _, id := range ids {
					whereArgs = append(whereArgs, id)
				}
			} else if strArr, ok := elems.([]string); ok {
				for _, id := range strArr {
					whereArgs = append(whereArgs, id)
				}
			} else {
				whereArgs = append(whereArgs, elems)
			}
		}
	}
	whereSql := strings.Builder{}
	for index, key := range whereKeys {
		if index == 0 {
			whereSql.WriteString(fmt.Sprintf(" where 1=1 %s ", key))
		} else {
			whereSql.WriteString(fmt.Sprintf(" %s ", key))
		}
	}
	return whereKeys, whereArgs, whereSql.String()
}
